﻿function MessageCenterAlerts($, ko, options) {

    var serviceFramework = $.ServicesFramework(options.ModuleId);
    var baseServicePath = serviceFramework.getServiceRoot(options.ModuleName);
    var countsPath = baseServicePath + "counts/get";

    var enablePopupForMessages = options.EnablePopupForMessages;
    var enablePopupForNotifications = options.EnablePopupForNotifications;
    var enableUpdateOfUsersControl = options.EnableUpdateOfUsersControl;
    var templates = options.templates;
    var milisecondsUntilInitalDisplay = options.MilisecondsUntilInitalDisplay;
    var milisecondsBetweenChecks = options.MilisecondsBetweenChecks;
    var milisecondsToDisplay = options.MilisecondsToDisplay;
    var effect = options.Effect;
    var effectDuration = options.EffectDuration;
    var messagesElementSelector = '#dnn_dnnUser_messageLink';
    var notificationsElementSelector = '#dnn_dnnUser_notificationLink';

    var containerElement = null;
    var viewModel = null;
    var autoCloseTimeout = null;

    function getCounts() {

        $.ajax({
            type: "GET",
            cache: false,
            url: countsPath,
            beforeSend: serviceFramework.setModuleHeaders
        }).done(onGetCountsSuccess);
    };

    function onGetCountsSuccess(data) {

        if (!data.success || !viewModel)
            return;

        viewModel.setCounts(data.counts);
    }
    
    function scheduleAutoClose() {
        clearTimeout(autoCloseTimeout);
        autoCloseTimeout = setTimeout(function () {
            viewModel.show(false);
        }, milisecondsToDisplay);  
    }
    
    function cancelAutoClose() {
        clearTimeout(autoCloseTimeout);   
    }
     
    function messageCenterAlertsViewModel() {
        
        var self = this;

        self.notificationCount = ko.observable(0);
        self.messageCount = ko.observable(0);
        self.show = ko.observable(false);

        self.setCounts = function (data) {

            if ((enablePopupForNotifications && (self.notificationCount() < data.notificationCount)) || (enablePopupForMessages && (self.messageCount() < data.messageCount))) {
                scheduleAutoClose();
                self.show(true);
            }
            else if(!self.notificationCount() && !self.messageCount()) {
                self.show(false);
            }
                
            self.notificationCount(data.notificationCount);
            self.messageCount(data.messageCount);
        };

        self.close = function () {
            cancelAutoClose();
            self.show(false);
        };

        self.mouseOver = function() {
            cancelAutoClose();
        };

        self.mouseOut = function() {
            scheduleAutoClose();
        };

        if(enableUpdateOfUsersControl && templates) {
            self.messageCount.subscribe(function (newValue) {
                var template = (newValue ? templates.messages : templates.noMessages) + '';
                $(messagesElementSelector).html(template.replace('{0}', newValue));
            });
            
            self.notificationCount.subscribe(function (newValue) {
                var template = (newValue ? templates.notifications : templates.noNotifications) + '';
                $(notificationsElementSelector).html(template.replace('{0}', newValue));
            });
        }
    }

    this.init = function (elementId, initialCounts) {

        containerElement = $(elementId).appendTo("body");

        viewModel = new messageCenterAlertsViewModel();

        ko.bindingHandlers.toggleVisible = {
            init: function (element, valueAccessor) {
                var shouldDisplay = valueAccessor();
                $(element).toggle(shouldDisplay);
            },
            update: function (element, valueAccessor) {
                // On update, hide/show
                var shouldDisplay = valueAccessor();
                if (!effect) effect = 'none';
                switch (effect.toLowerCase()) {
                    case "fade":
                        shouldDisplay ? $(element).fadeIn(effectDuration) : $(element).fadeOut(effectDuration);
                        break;
                    case 'slide':
                        shouldDisplay ? $(element).slideDown(effectDuration) : $(element).slideUp(effectDuration);
                        break;
                    default:
                        shouldDisplay ? $(element).show() : $(element).hide();
                        break;
                }
            }
        };
        
        ko.bindingHandlers.stopBinding = {
            init: function () {
                return { controlsDescendantBindings: true };
            }
        };
        
        ko.virtualElements.allowedBindings.stopBinding = true;

        ko.applyBindings(viewModel, containerElement[0]);

        if(!milisecondsBetweenChecks || milisecondsBetweenChecks < 1000)
            milisecondsBetweenChecks = 1000;

        if (milisecondsUntilInitalDisplay) {
            setTimeout(function () {
                viewModel.setCounts(initialCounts);
                setInterval(getCounts, milisecondsBetweenChecks);
            }, milisecondsUntilInitalDisplay);
        }
        else {
            viewModel.setCounts(initialCounts);
            setInterval(getCounts, milisecondsBetweenChecks);
        }
    };
};
